public class Solution2 {
        //输入一个链表，输出该链表中倒数第k个结点
    //方法一
        public int kthToLast(ListNode head, int k) {
             if(k <= 0 || k > size(head)) {
                 return -1;
             }
            int len = size(head);
            int count = 0;
            ListNode cur = head;
            while(count < len -k) {
                cur = cur.next;
                count++;
            }
            return cur.val;
        }
        private int size(ListNode head) {
            int count = 0;
            while(head != null) {
                count++;
                head = head.next;
            }
            return count;
        }
        //方法二
        public int kthToLast2(ListNode head, int k) {
            if(k <= 0) {
                return -1;
            }
            ListNode fast = head;
            ListNode slow = head;
            int count = k - 1;
            while(count != 0) {
                fast = fast.next;
                if(fast == null) {
                    return -1;
                }
                count--;
            }
            while(fast.next != null) {
                fast = fast.next;
                slow = slow.next;
            }
            return slow.val;
        }
}
